import {makeId} from "./idMaker";
import {Context, Room} from "./context";
import * as WebSocket from 'ws';

export class RoomManager {
  private busyRooms: Map<number, Room> = new Map<number, Room>();
  private idleRooms: Map<number, Room> = new Map<number, Room>();

  public room: Room;

  getRoomById() {

  }

  getRoomByRandom() {
    if (this.idleRooms.size === 0) {

    }
  }

  createRoom(maxCount: number) {
    const room = new Room();
    room.maxCount = maxCount;
    room.id = this.randomId();
    while (this.idleRooms.get(room.id)) {
      room.id = this.randomId();
    }
    this.idleRooms.set(room.id, room);
    this.room = room;
    return room;
  }

  private randomId() {
    return Math.floor(Math.random()) * 9000 + 1000;
  }
}

export class ContextManager {
  private ctxs: Map<WebSocket, Context> = new Map<WebSocket, Context>();

  createContext(ws: WebSocket) {
    const ctx = new Context();
    ctx.id = makeId();
    ctx.ws = ws;
    this.ctxs.set(ws, ctx);
    return ctx
  }

  getCtxByWs(ws: WebSocket): Context {
    return this.ctxs.get(ws);
  }
}

export class MatchManager {
  matchCount = 2;
  private matchPlayers: Array<Context> = [];

  match(ctx: Context) {
    this.matchPlayers.push(ctx);
    if (this.matchPlayers.length === this.matchCount) {
      this.matchSuccess();
    }
  }

  matchSuccess() {
    const ctx1 = this.matchPlayers.shift();
    const ctx2 = this.matchPlayers.shift();
    const room = roomManager.createRoom(this.matchCount);
    ctx1.room = room;
    ctx2.room = room;
    room.connections.push(ctx1);
    room.connections.push(ctx2);
    room.isStart = true;
    room.broadcast('joinSuc', [ctx1.user, ctx2.user])
    // room.broadcast()
  }
}

export const roomManager = new RoomManager();
export const contextManager = new ContextManager();
export const matchManager = new MatchManager();
